package com.xiaobai.common.utils.tool;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

/**
 * 生成二维码工具类
 * @date 2024/9/30 14:11
 */
public class QRCodeGenerator {
    private static final String CHARSET = "UTF-8";
    private static final String FORMAT_NAME = "PNG";
    private static final String FILE_TYPE = "微软雅黑";
    /**
     * @description 生成二维码
     * @param text 二维码内容
     * @param remark 二维码描述
     * @param path 二维码保存路径
     * @param logoFile 二维码logo文件
     * @param width 二维码宽度
     * @param height 二维码高度
     */
    public static void generateQRCode(String text, String remark, String path, File logoFile, int width, int height) throws Exception {
        // 设置二维码参数
        //com.google.zxing.EncodeHintType：编码提示类，枚举类型
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //EncodeHintType.CHARACTER_SET：设置字符编码类型
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        //EncodeHintType.ERROR_CORRECTION：设置纠错级别
        //ErrorCorrectionLevel：纠错级别，【L：%7】【M：15%】【Q：25%】[H：30%]
        //默认为L级别，纠错级别不同，生成的图案不同，但扫描结果一致
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        //EncodeHintType.MARGIN：设置二维码边距，单位像素
        hints.put(EncodeHintType.MARGIN, 1);
        //创建工厂类
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        // 创建BitMatrix对象
        //指定二维码类型和参数，返回对应的Writter进行编码后的二维码对象
        BitMatrix matrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);

        // 动态计算增加的高度用于备注文本
        int textHeight = (remark != null && !remark.isEmpty()) ? 30 : 0;

        // 创建带有二维码和备注文本的 BufferedImage
        BufferedImage qrImage = new BufferedImage(width, height + textHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = qrImage.createGraphics();
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height + textHeight); // 设置背景为白色

        // 绘制二维码到 BufferedImage
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                qrImage.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        // 添加Logo到二维码
        if (logoFile != null && logoFile.exists()) {
            addLogoToQRCode(qrImage, logoFile, width, height);
        }

        // 添加备注文本
        if (remark != null && !remark.isEmpty()) {
            addTextToQRCode(qrImage, remark, width, height, textHeight);
        }

        // 保存二维码图片到指定路径
        Path filePath = Paths.get(path);
        Files.createDirectories(filePath.getParent()); // 确保目录存在
        ImageIO.write(qrImage, FORMAT_NAME, new File(path));
    }

    // 添加Logo到二维码
    private static void addLogoToQRCode(BufferedImage qrImage, File logoFile, int qrWidth, int qrHeight) throws Exception {
        // 读取Logo图片
        BufferedImage logoImage = ImageIO.read(logoFile);

        // 计算Logo的缩放比例和新宽高
        int logoWidth = Math.min(logoImage.getWidth(), qrWidth / 5);  // 缩小至二维码宽度的1/5
        int logoHeight = Math.min(logoImage.getHeight(), qrHeight / 5);

        // 计算Logo绘制的左上角位置，使其居中
        int x = (qrWidth - logoWidth) / 2;
        int y = (qrHeight - logoHeight) / 2;

        // 绘制白色边框背景
        Graphics2D g2 = qrImage.createGraphics();
        g2.setColor(Color.WHITE);
        g2.fillRoundRect(x - 5, y - 5, logoWidth + 10, logoHeight + 10, 10, 10);

        // 绘制Logo到二维码中心
        g2.drawImage(logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH), x, y, null);
        g2.dispose();
    }

    // 在二维码底部添加文本
    private static void addTextToQRCode(BufferedImage image, String text, int width, int qrHeight, int textHeight) throws UnsupportedEncodingException {
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.BLACK);
        g2.setFont(new Font(FILE_TYPE, Font.PLAIN, 20));  // 设置字体

        // 获取文本的宽度以便居中对齐
        FontMetrics fm = g2.getFontMetrics();
        int textWidth = fm.stringWidth(text);
        int x = (width - textWidth) / 2;

        // 调整 y 坐标位置，将文本稍微上移
        int padding = 10;  // 增加一个 padding 值，让文本上移一点，避免贴得太近
        int y = qrHeight + (textHeight - fm.getHeight()) / 2 + fm.getAscent() - padding;

        // 绘制文本
        g2.drawString(text, x, y);
        g2.dispose(); // 释放资源
    }



    /**
     * 解析二维码
     *
     * @param file
     *            二维码图片
     * @return 解析文本
     * @throws Exception
     */
    public static String decode(File file) throws Exception {
        //将二维码图片加载为BufferedImage
        BufferedImage bufferedImage = ImageIO.read(file);
        if (bufferedImage == null) {
            return null;
        }
        //创建BufferedImageLuminanceSource
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
        //使用HybridBinarizer将LuminanceSource转换为二进制位图BinaryBitmap
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        //使用工厂类
        MultiFormatReader reader = new MultiFormatReader();
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        //解码
        result = reader.decode(bitmap, hints);
        //获取内容
        return result.getText();
    }

    /**
     * 解析二维码
     *
     * @param path
     *            二维码图片地址
     * @return
     * @throws Exception
     */
    public static String decode(String path) throws Exception {
        return QRCodeGenerator.decode(new File(path));
    }


}
